#include "ScnsInclude.h"
#include "JctoInclude.h"
#include "init.h"
#include <direct.h>


int main(int argc,char**argv,char**envp)
{
    JctoArgv jctoArgv;
    jctoArgvDecode(&jctoArgv,argc,argv,envp);
    jctoArgvSave(&jctoArgv,stdout);
    static const uint64 flashSize=10244ULL*10244ULL;
    uint8*flash=malloc(flashSize);
    SCNS_ASSERT_ON_RUN(flash);
    FILE*fp=fopen(jctoArgv.loadModelDir,"rb");
    SCNS_ASSERT_ON_RUN(fp);
    uint64 addrList[32][2];
    int addrListCnt=jctoHexImport(fp,flash,flashSize,addrList);
    fclose(fp);
    printf("addrListCnt=%d\n",addrListCnt);

#if 0
    if(addrListCnt!=0)
    {
        int FLASH_INFO_ADDR=0;
        for(int addrI=0;addrI<addrListCnt;++addrI)
        {
            if(addrList[addrI][0]==0x18000||addrList[addrI][1]==0x18000+256)
            {
                SCNS_ASSERT_ON_RUN(FLASH_INFO_ADDR==0);
                FLASH_INFO_ADDR=0x18000;
            }
            else if(addrList[addrI][0]==0X62000||addrList[addrI][1]==0X62000+256)
            {
                SCNS_ASSERT_ON_RUN(FLASH_INFO_ADDR==0);
                FLASH_INFO_ADDR=0X62000;
            }
        }
        SCNS_ASSERT_ON_RUN(FLASH_INFO_ADDR!=0);
        const uint8(*chipIdMap)[8]=(const uint8(*)[8])(flash+FLASH_INFO_ADDR+64);
        const char*name=(char*)(flash+FLASH_INFO_ADDR);
        const uint8 chipIdMapCnt=nnoDeviceGetChipIdCnt(chipIdMap);
        hxPrintfFL("%#04&*^8hhX\n",chipIdMapCnt*8,chipIdMap);
        hxPrintfFL("%s\n",name);
        nnoDeviceFlashCheck(flash,(FLASH_INFO_ADDR),(uint16*)(flash+FLASH_INFO_ADDR+128),NULL);
        if(addrList[addrListCnt-1][0]==FLASH_INFO_ADDR||addrList[addrListCnt-1][1]==FLASH_INFO_ADDR+256)
        {
            addrList[addrListCnt-1][1]=FLASH_INFO_ADDR+256;
        }
        else if(addrList[addrListCnt-1][0]<FLASH_INFO_ADDR)
        {
            ++addrListCnt;
            addrList[addrListCnt-1][0]=FLASH_INFO_ADDR;
            addrList[addrListCnt-1][1]=FLASH_INFO_ADDR+256;
        }
        hxPrintfFL("%#010&*^2X\n",2*(addrListCnt),addrList);
        const uint16 crc16=((const uint16*)(flash+FLASH_INFO_ADDR+128))[0];
        if(strlen(jctoArgv.outputDir)>=0)
        {
            char outDir[8192];
            jctoMkdir(outDir,1,2,jctoArgv.outputDir,"backup");
            char fileName[8192];
            hxSNPrintf(fileName,sizeof(fileName),"%s/%#06X.hex",outDir,crc16);
            FILE*fp2=fopen(fileName,"wb");
            jctoHexExport(fp2,flash,addrList,addrListCnt);
            fclose(fp2);
        }

        {
            FILE*fp3=fopen(jctoArgv.loadModelDir,"wb");
            addrList[0][1]=addrList[addrListCnt-1][1];
            addrListCnt=1;
            jctoHexExport(fp3,flash,addrList,addrListCnt);
            fclose(fp3);
        }
    }
#endif
    free(flash);
    return 0;
}
